/**
 *  基础 高德地图操作
 */
import GPS from "./gps.js";

//点
const mStyle = {
  normal: {
    //点的默认样式
    icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
  },
  selected: {
    //点的选中样式
    icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
  },
};
//海量点
const massStyle = {
  normal: {
    url: 'https://webapi.amap.com/images/mass/mass0.png',
    size: [11, 11],
    anchor: [6, 6]
  },
  selected: {
    url: 'https://webapi.amap.com/images/mass/mass1.png',
    size: [11, 11],
    anchor: [6, 6]
  },
};
//线
const lStyle = {
  normal: {
    //线的默认样式
    strokeColor: "#f90008", //线条颜色
    strokeOpacity: 0.9,
    strokeStyle: "solid", //实线:solid，虚线:dashed
    strokeWeight: 8,
  },
  selected: {
    //线的选中样式
    strokeColor: "#00D3FC", //线条颜色
    strokeOpacity: 0.9,
    strokeStyle: "solid", //实线:solid，虚线:dashed
    strokeWeight: 8,
  },
};
//面
const pStyle = {
  normal: {
    //面的默认样式
    fillColor: "#00B2D5", //填充颜色
    fillOpacity: 0.5,
    strokeColor: "#00D3FC", //线条颜色
    strokeOpacity: 0.9,
    strokeStyle: "solid", //实线:solid，虚线:dashed
    strokeWeight: 2,
  },
  selected: {
    //面的选中样式
    fillColor: "#FFAD40", //填充颜色
    fillOpacity: 0.8,
    strokeColor: "#fff", //线条颜色
    strokeOpacity: 1,
    strokeStyle: "solid", //实线:solid，虚线:dashed
    strokeWeight: 3,
    // extrusionHeight: 20, //设置多边形是否拉伸为的立面体高度值
    // wallColor: '#25ffea', //立面体侧面颜色
    // roofColor: '#00D3FC' //立面体侧面颜色
  },
};

export default class MapClass {
  constructor(map) {
    // 声明地图对象
    this.map = map;
    // 所有覆盖物分类集合
    this.layerKeys = [];
    // 当前选中的覆盖物对象
    this.activeTarget = null;
    // 模拟海量点选中的对象
    this.activeMarker = null;
  }

  // 批量添加点  array格式：[{id:1, point:[120.3,30.2]}]
  addMarkers(
    key = "marker",
    array = [],
    clickEvent = null,
    normalStyle = {},
    selectedStyle = {}
  ) {
    // console.log("MapClass批量绘制点：", key, array);
    if (!array || !array.length) return;
    let list = [];
    let normal = Object.assign({}, mStyle.normal, normalStyle);
    let selected = Object.assign({}, mStyle.selected, selectedStyle);
    // 循环创建
    array.map((dot) => {
      if (
        !dot.id ||
        !dot.point ||
        dot.point.length < 2 ||
        Array.isArray(dot.point[0])
      ) {
        // console.log("MapClass非法点数据：", dot);
        return dot;
      }
      dot.key = key;
      dot.normalStyle = Object.assign({}, normal, dot.normalStyle);
      dot.selectedStyle = Object.assign({}, selected, dot.selectedStyle);
      const content = `<div class="marker-icon" style="background:${dot.normalStyle.color}"><div>`;
      const marker = new AMap.Marker({
        position: GPS.WGS84toGCJ02(...dot.point),
        title: dot.name || "--",
        anchor: "bottom-center",
        extData: dot,
        ...dot.normalStyle,
        content: dot.normalStyle.color ? content : null,
      });
      marker.on("click", (e) => {
        // 选中点位
        this.activeLayer(e);
        // 抛出事件
        if (clickEvent && typeof clickEvent == "function") {
          clickEvent(e.target.getExtData());
        }
      });
      list.push(marker);
    });
    if (!this.layerKeys[key]) this.layerKeys[key] = [];
    this.layerKeys[key] = this.layerKeys[key].concat(list);
    this.map.add(list);
    this.map.setFitView(list);
  }
  // 批量添加点  array格式：[{id:1, point:[120.3,30.2]}]
  addMassMarkers(
    key = "massMarker",
    array = [],
    clickEvent = null,
    normalStyle = {},
    selectedStyle = {}
  ) {
    console.log("MapClass批量绘制点：", key, array);
    if (!array || !array.length) return;
    let list = [];
    let normal = Object.assign({}, massStyle.normal, normalStyle);
    let selected = Object.assign({}, massStyle.selected, selectedStyle);
    // 循环创建
    array.map((dot) => {
      if (
        !dot.id ||
        !dot.point ||
        dot.point.length < 2 ||
        Array.isArray(dot.point[0])
      ) {
        console.log("MapClass非法点数据：", dot);
        return dot;
      }
      dot.key = key;
      const data = {
        lnglat: GPS.WGS84toGCJ02(...dot.point),
        name: dot.name,
        id: dot.id,
        style: 0,
        selected: selected,
        extData: dot
      }
      list.push(data);
    });

    let mass = new AMap.MassMarks(list, {
      opacity: 0.8,
      zIndex: 9999,
      cursor: 'pointer',
      style: normal
    })
    mass.on("click", (e) => {
      // 选中点位
      this.activeLayer(e);

      // 抛出事件
      if (clickEvent && typeof clickEvent == "function") {
        clickEvent(e.data.extData);
      }
    })
    if (!this.layerKeys[key]) this.layerKeys[key] = [];
    this.layerKeys[key] = mass;
    mass.setMap(this.map)
  }
  // 批量添加线  array格式：[{id:1, point:[[120.3,30.2],[120.3,30.2]], normalStyle:{}, selectedStyle:{}}]
  addPolylines(
    key = "polyline",
    array = [],
    clickEvent = null,
    normalStyle = {},
    selectedStyle = {}
  ) {
    console.log("MapClass批量绘制线：", key, array);
    if (!array || !array.length) return;
    let list = [];
    let normal = Object.assign({}, lStyle.normal, normalStyle);
    let selected = Object.assign({}, lStyle.selected, selectedStyle);
    // 循环创建
    array.map((dot) => {
      if (!dot.point || dot.point.length < 2 || !Array.isArray(dot.point[0])) {
        console.log("MapClass非法线数据：", dot);
        return dot;
      }
      dot.key = key;
      dot.normalStyle = Object.assign({}, normal, dot.normalStyle);
      dot.selectedStyle = Object.assign({}, selected, dot.selectedStyle);
      const polyline = new AMap.Polyline({
        path: dot.point.map((point) => GPS.WGS84toGCJ02(...point)),
        extData: dot,
        ...dot.normalStyle,
      });
      polyline.on("click", (e) => {
        // 选中点位
        this.activeLayer(e);
        // 抛出事件
        if (clickEvent && typeof clickEvent == "function") {
          clickEvent(e.target.getExtData());
        }
      });
      list.push(polyline);
    });
    if (!this.layerKeys[key]) this.layerKeys[key] = [];
    this.layerKeys[key] = this.layerKeys[key].concat(list);
    this.map.add(list);
    this.map.setFitView(list);
  }
  // 批量添加面  array格式：[{id:1, point:[[120.3,30.2],[120.3,30.2],[120.3,30.2]], normalStyle:{}, selectedStyle:{}}]
  addPolygons(
    key = "polygon",
    array = [],
    clickEvent = null,
    normalStyle = {},
    selectedStyle = {}
  ) {
    console.log("MapClass批量绘制面：", key, array);
    if (!array || !array.length) return;
    let list = [];
    let normal = Object.assign({}, pStyle.normal, normalStyle);
    let selected = Object.assign({}, pStyle.selected, selectedStyle);
    // 循环创建
    array.map((dot, index) => {
      if (
        !dot.id ||
        !dot.point ||
        dot.point.length < 3 ||
        !Array.isArray(dot.point[0])
      ) {
        console.log("MapClass非法面数据：", dot);
        return dot;
      }
      dot.key = key;
      dot.normalStyle = Object.assign({}, normal, dot.normalStyle);
      dot.selectedStyle = Object.assign({}, selected, dot.selectedStyle);
      var colorList = ["#00F7FF", "#FFD846", "#2FFF98", "#467EFF"];
      if (key === "pq") {
        dot.normalStyle.fillColor = colorList[index];
        dot.selectedStyle.fillColor = colorList[index];
      } else if (key === "wg") {
        dot.normalStyle.strokeStyle = "dashed";
      }
      const polygon = new AMap.Polygon({
        path: dot.point.map((point) => GPS.WGS84toGCJ02(...point)),
        extData: dot,
        ...dot.normalStyle,
      });
      polygon.on("click", (e) => {
        // 选中点位
        this.activeLayer(e);
        // 抛出事件
        if (clickEvent && typeof clickEvent == "function") {
          clickEvent(e.target.getExtData());
        }
      });
      list.push(polygon);
    });
    if (!this.layerKeys[key]) this.layerKeys[key] = [];
    this.layerKeys[key] = this.layerKeys[key].concat(list);
    this.map.add(list);
    this.map.setFitView(list);
  }
  // 删除某个分类
  removeLayer(key) {
    console.log("MapClass删除分类：", key);
    if (this.activeTarget && key == this.activeTarget.getExtData()
      .key) {
      //处理当前选中被删除
      this.inactiveLayer();
    }
    const list = this.layerKeys[key];
    if (!list) return
    if (Array.isArray(list)) {
      for (let i = 0; i < list.length; i++) {
        let target = list[i];
        target.clearEvents("click");
        this.map.remove(target);
      }
    } else {
      // list.clearEvents("click");
      list.clear()
      //处理当前选中被删除
      this.activeMarker && this.map.remove(this.activeMarker)
      this.activeMarker = null
    }
    this.layerKeys[key] = [];
  }
  // 根据ID选中当前对象
  activeLayerById(id, key) {
    const list = this.layerKeys[key];
    if (!list) return
    if (Array.isArray(list)) {
      for (let i = 0; i < list.length; i++) {
        const target = list[i];
        if (target.getExtData().id == id) {
          this.activeLayer(target);
          return target.getExtData()
        }
      }
    } else {
      for (let i = 0; i < list.target.VL.length; i++) {
        const dot = list[i];
        if (dot.id == id) {
          this.activeLayer({
            data: dot,
            target: {
              CLASS_NAME: 'AMap.MassMarks'
            }
          });
          return dot
        }
      }
    }
  }
  // 选中当前点 e:点击事件或者对象
  activeLayer(e, key='marker') {
    // 取消上个点击
    this.inactiveLayer();
    let target = null
    if(typeof e == 'number') {
      // 外部传入id
      if(!this.layerKeys[key]) return;
      target = this.layerKeys[key].find(item => item._opts.extData.id == e )
    }else{
      target = e.target || e;
    }
    // 选中当前点击
    if (target.type && target.type == "AMap.Marker") {
      const extData = target.getExtData();
      // 可以增加，需同步增加取消选中set
      target.setIcon(extData.selectedStyle.icon);
      this.activeTarget = target;
      // 存在问题setOptions属性更新，UI不渲染
      // target.setOptions(extData.selectedStyle)
      // console.log(target.getOptions());
    } else if (target.CLASS_NAME && target.CLASS_NAME == 'AMap.MassMarks') {
      // 模拟选中点位
      const selIcon = new AMap.Icon({
        size: e.data.selected.size,
        image: e.data.selected.url,
        imageSize: e.data.selected.size,
      });
      if (this.activeMarker) {
        this.activeMarker.setTitle(e.data.name)
        this.activeMarker.setExtData(e.data.extData)
        this.activeMarker.setPosition(e.data.lnglat)
        this.activeMarker.setOffset(new AMap.Pixel(-e.data.selected.anchor[0], -e.data.selected.anchor[1]))
        this.activeMarker.setIcon(selIcon)
      } else {
        console.log(e);
        this.activeMarker = new AMap.Marker({
          map: this.map,
          title: e.data.name,
          position: e.data.lnglat,
          icon: selIcon,
          offset: new AMap.Pixel(-e.data.selected.anchor[0], -e.data.selected.anchor[1])
        })
      }
    } else {
      const extData = target.getExtData();
      target.setOptions(extData.selectedStyle);
      this.activeTarget = target;
    }

  }
  // 取消当前选中
  inactiveLayer() {
    // TODO
    if (!this.activeTarget) {
      return;
    }
    const extData = this.activeTarget.getExtData();
    if (this.activeTarget.type == "AMap.Marker") {
      this.activeTarget.setIcon(extData.normalStyle.icon);
    } else {
      this.activeTarget.setOptions(extData.normalStyle);
    }
    this.activeTarget = null;
  }
  // 清空地图
  removeAll() {
    for (let i = 0; i < this.layerKeys.length; i++) {
      this.removeLayer(this.layerKeys[i]);
    }
  }
}
